﻿using HCApp.UI.Windows.Views;
using ImTools;
using LinnerToolkit.Core.Navigation;
using MainAppEntryPrismWpf.Utilities;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using SCDB.ViewModels;
using Syncfusion.Data.Extensions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MainAppEntryPrismWpf.Views
{
    /// <summary>
    /// HistoryReviewPage.xaml 的交互逻辑
    /// </summary>
    public partial class HistoryReviewPage :  ContentPageBase
    {
        public DataClassesSCDBDataContext SCDBDataContent;

        float zCL = 0;
        float zGZ = 0;

        //白班总产量和工资
        float zWhiteCL = 0;
        float zWhiteGZ = 0;

        //夜班总产量和工资
        float zNightCL = 0;
        float zNightGZ = 0;
      
        //白班平均产量和工资
        float averageWhiteCL = 0;
        float averageWhiteGZ = 0;

        //夜班平均产量和工资
        float averageNightCL = 0;
        float averageNightGZ = 0;



        float averageCL = 0;
        float averageGZ = 0;

        DateTime exportedDateTime;


        ObservableCollection<DansiDailySalary> dansiDailySalaries = new ObservableCollection<DansiDailySalary>();

        ObservableCollection<ZhiXianDailyOutputRepo> zhiXianDailyOutputRepo= new ObservableCollection<ZhiXianDailyOutputRepo>();

        ObservableCollection<ZhiXianDailyOutputRepo> zhiXianMultiOutputRepo = new ObservableCollection<ZhiXianDailyOutputRepo>();

        ObservableCollection<ZhiXianPeriodOutputSalaryRepo> zhiXianPeriodOutputSalaryRepo = new ObservableCollection<ZhiXianPeriodOutputSalaryRepo>();


        public HistoryReviewPage()
        {
            InitializeComponent();

            SCDBDataContent = new DataClassesSCDBDataContext();
            exportedDateTime= DateTime.Now;


            //datagridDaily.ItemsSource = (from data in SCDBDataContent.DSZX_CLGZB
            //                        select data).ToList();
            //datagrid.ItemsSource = (from data in SCDBDataContent.DSZX_CPCRKB
            //                        where data.CJH == "制线"
            //                        select data).ToList();
        }

        private void ContentPageBase_Loaded(object sender, RoutedEventArgs e)
        {
           
            //  getComDataTimer.Start();

        }

        protected override void InternalOnNavigatedFrom(AppNavigationParameters parameters)
        {
           
            base.InternalOnNavigatedFrom(parameters);

        }

        private void dailySalaryClick(object sender, RoutedEventArgs e)
        {
            string dllFilePath = Assembly.GetExecutingAssembly().Location;
           // string dllDirectoryPath = Path.GetDirectoryName(dllFilePath);        


            var filePath = @"d:\工资\";

            DateTime certainDate = Convert.ToDateTime(sfDatePicker.Value?.ToString("yyyy-MM-dd"));
            DateTime EndcertainDate = Convert.ToDateTime(sfDatePicker5.Value?.ToString("yyyy-MM-dd"));

            string dateRangeStr = $"从 {certainDate.ToString("yyyy-MM-dd")} 到 {EndcertainDate.ToString("yyyy-MM-dd")}";

            var fileName = $"工资{certainDate.ToString("yyyyMMddHHmmss")}.xlsx";
            var header = new List<ExcelHeader>() {

                        //  new ExcelHeader (){ FirstCol=0, LastCol=4, FirstRow=0, LastRow=0, Value="制线生产日工资表" },//(第一行)(跨列0-6)
                         new ExcelHeader (){ FirstCol=0, LastCol=4, FirstRow=0, LastRow=0, Value="单丝生产员工工资表" },//(第一行)(跨列0-6)
                       //   new ExcelHeader (){ FirstCol=3, LastCol=5, FirstRow=1, LastRow=1, Value="日期："+exportedDateTime.ToShortDateString() },//(第二行)(跨列0-6)
                           new ExcelHeader (){ FirstCol=2, LastCol=4, FirstRow=1, LastRow=1, Value="日期："+dateRangeStr },//(第二行)(跨列0-6)
        
                            new ExcelHeader (){ FirstCol=0, LastCol=0, FirstRow=2, LastRow=2, Value="工号" },//第一列，跨两行(2-3)
		                     new ExcelHeader (){ FirstCol=1, LastCol=1, FirstRow=2, LastRow=2, Value="姓名" },//跨两列(1,2),同一行(第三行)
		                     new ExcelHeader (){ FirstCol=2, LastCol=2, FirstRow=2, LastRow=2, Value="规格" },
                             new ExcelHeader (){ FirstCol=3, LastCol=3, FirstRow=2, LastRow=2, Value="产量" },
                            new ExcelHeader (){ FirstCol=4, LastCol=4, FirstRow=2, LastRow=2, Value="工资" },

             }; 

            var data = new ExcelData<DansiDailySalary> { StartCol = 0, StartRow = 3, Data = dansiDailySalaries  };
            ExcelHelper.ExportExcel(filePath, fileName, header, data);          
            MessageBox.Show(@"已成功导出到D:\工资\！");

             datagridDaily.ItemsSource = dansiDailySalaries;


        }

        private void dailyRepoClick(object sender, RoutedEventArgs e)
        {
            DateTime certainDate = Convert.ToDateTime(sfDatePicker2.Value?.ToString("yyyy-MM-dd"));
            var filePath = @"d:\产量\";
            var fileName = $"产量{certainDate.ToString("yyyyMMddHHmmss")}.xlsx";
            var header = new List<ExcelHeader>() {

            new ExcelHeader (){ FirstCol=0, LastCol=4, FirstRow=0, LastRow=0, Value="单丝日产量表" },//(第一行)(跨列0-6)
            new ExcelHeader (){ FirstCol=2, LastCol=3, FirstRow=1, LastRow=1, Value="日期："+exportedDateTime.ToShortDateString() },//(第二行)(跨列0-6)
        
               new ExcelHeader (){ FirstCol=0, LastCol=0, FirstRow=2, LastRow=2, Value="班次" },//第一列，跨两行(2-3)
		                     //new ExcelHeader (){ FirstCol=1, LastCol=1, FirstRow=2, LastRow=2, Value="开机3台时间" },//跨两列(1,2),同一行(第三行)
		                     //new ExcelHeader (){ FirstCol=2, LastCol=2, FirstRow=2, LastRow=2, Value="开机四台时间" },
                       //      new ExcelHeader (){ FirstCol=3, LastCol=3, FirstRow=2, LastRow=2, Value="开机5台时间" },

                            //new ExcelHeader (){ FirstCol=4, LastCol=4, FirstRow=2, LastRow=2, Value="产品规格" },
                            //  new ExcelHeader (){ FirstCol=5, LastCol=5, FirstRow=2, LastRow=2, Value="产量(kg)" },
                            //new ExcelHeader (){ FirstCol=6, LastCol=6, FirstRow=2, LastRow=2, Value="工资(元)" },

                            new ExcelHeader (){ FirstCol=1, LastCol=1, FirstRow=2, LastRow=2, Value="产品规格" },
                              new ExcelHeader (){ FirstCol=2, LastCol=2, FirstRow=2, LastRow=2, Value="产量(kg)" },
                            new ExcelHeader (){ FirstCol=3, LastCol=3, FirstRow=2, LastRow=2, Value="工资(元)" },

              };



            var data = new ExcelData<ZhiXianDailyOutputRepo> { StartCol = 0, StartRow = 3, Data = zhiXianDailyOutputRepo };
            ExcelHelper.ExportExcel(filePath, fileName, header, data);

            MessageBox.Show(@"已成功导出到D:\产量\！");


        }

        private void btnGet_Click(object sender, RoutedEventArgs e)
        {
            DateTime certainDate = Convert.ToDateTime(sfDatePicker.Value?.ToString("yyyy-MM-dd"));

            DateTime certainDateWhiteStart = certainDate.AddHours(7);
            DateTime certainDateWhiteEnd = certainDateWhiteStart.AddHours(12);

            DateTime certainDateNightStart = certainDate.AddHours(19);
            DateTime certainDateNightEnd = certainDateNightStart.AddHours(12);
            DateTime certainDateNext = certainDate.AddDays(1);



            //最后一天的开始结束日时间段

            DateTime EndcertainDate = Convert.ToDateTime(sfDatePicker5.Value?.ToString("yyyy-MM-dd"));

            DateTime EndcertainDateWhiteStart = EndcertainDate.AddHours(7);

            DateTime EndcertainDateNext = EndcertainDateWhiteStart.AddDays(1);


            exportedDateTime = certainDate;



            //#region  pause

            //zCL = 0;
            // zGZ = 0;

            ////查询满足当前日期条件的总产量和总成本

            ////分开计算 白班产量 和白班员工工资

            //zWhiteCL = 0;
            //zWhiteGZ = 0;
            //var certainDayWhiteData = (from data in SCDBDataContent.DSZX_CPCRKB 
            //                       where data.CJH == "制线" && data.RKSJ >= certainDateWhiteStart && data.RKSJ < certainDateWhiteEnd
            //                           select data).ToList();
            //if (certainDayWhiteData != null && certainDayWhiteData.Count > 0)
            //{
            //    for (int i = 0; i < certainDayWhiteData.Count; i++)
            //    {
            //        zWhiteCL = (float)certainDayWhiteData[i].CPZL + zWhiteCL;
            //        zWhiteGZ = (float)certainDayWhiteData[i].HSGZ + zWhiteGZ;
            //    }
            //}

            ////查询满足当前签到日期的所有记录  更新白班工资表

            //List<DSZX_CLGZB> certainDayWhiteSignedList = (from data in SCDBDataContent.DSZX_CLGZB
            //                                         where data.CJH == "制线" && data.SCRQ >= certainDate && data.SCRQ < certainDateNext&&data.BC=="白班"
            //                                         select data).ToList();


            //if (certainDayWhiteSignedList != null && certainDayWhiteSignedList.Count > 0)
            //{
            //    averageWhiteCL = zWhiteCL / certainDayWhiteSignedList.Count;
            //    averageWhiteGZ = zWhiteGZ / certainDayWhiteSignedList.Count;
            //    for (int i = 0; i < certainDayWhiteSignedList.Count; i++)
            //    {
            //        certainDayWhiteSignedList[i].SCCL = averageWhiteCL;
            //        certainDayWhiteSignedList[i].YGGZ = averageWhiteGZ;
            //        SCDBDataContent.SubmitChanges();
            //    }
            //}
            ////分开计算  夜班产量和 夜班工资

            //zNightCL = 0;
            //zNightGZ = 0;
            //var certainDayNightData = (from data in SCDBDataContent.DSZX_CPCRKB
            //                           where data.CJH == "制线" && data.RKSJ >= certainDateNightStart && data.RKSJ < certainDateNightEnd
            //                           select data).ToList();
            //if (certainDayNightData != null && certainDayNightData.Count > 0)
            //{
            //    for (int i = 0; i < certainDayNightData.Count; i++)
            //    {
            //        zNightCL = (float)certainDayNightData[i].CPZL + zNightCL;
            //        zNightGZ = (float)certainDayNightData[i].HSGZ + zNightGZ;
            //    }
            //}

            ////查询满足当前签到日期的所有记录  更新夜班工资表

            //List<DSZX_CLGZB> certainDayNightSignedList = (from data in SCDBDataContent.DSZX_CLGZB
            //                                              where data.CJH == "制线" && data.SCRQ >= certainDate && data.SCRQ < certainDateNext && data.BC == "夜班"
            //                                              select data).ToList();

            //if (certainDayNightSignedList != null && certainDayNightSignedList.Count > 0)
            //{
            //    averageNightCL = zNightCL / certainDayNightSignedList.Count;
            //    averageNightGZ = zNightGZ / certainDayNightSignedList.Count;
            //    for (int i = 0; i < certainDayNightSignedList.Count; i++)
            //    {
            //        certainDayNightSignedList[i].SCCL = averageNightCL+averageWhiteCL;
            //        certainDayNightSignedList[i].YGGZ = averageNightGZ+averageWhiteGZ;
            //        SCDBDataContent.SubmitChanges();
            //    }
            //}

            ////最后按照员工编号汇总单日工资 白班工资+夜班工资

            //#endregion

            dansiDailySalaries.Clear();


            
            List<DSZX_CLGZB> afterDaySignedList = (from data in SCDBDataContent.DSZX_CLGZB
                                                       //   where data.CJH == "制线" && data.SCRQ >= certainDate && data.SCRQ < certainDateNext
                                                   where data.CJH == "单丝" && data.SCRQ >= certainDate && data.SCRQ < EndcertainDateNext
                                                   select data).ToList();
            //


            var query3 = from el in afterDaySignedList.GroupBy(x => x.YGXM)
                         select new DansiDailySalary
                         {
                             YGXM = el.Key,
                             YGBH = (el.Where(a => a.YGXM == el.Key).First()).YGBH?.ToString("D4"),
                             SCCL =Math.Round( (double)(el.Sum(a => a.SCCL)),3),
                             YGGZ =Math.Round( (double)el.Sum(x => x.YGGZ),3),

                         };



            var query4 = from el in afterDaySignedList
                         select new DansiDailySalary
                         {
                             YGXM = el.YGXM,
                             YGBH = el.YGBH?.ToString("D4"),
                             CPGG=el.CPGG,
                             SCCL = (double)el.SCCL,
                             YGGZ = (double)el.YGGZ,

                         };
            var query3List = query3.ToList().OrderBy(a => a.YGBH);
          //  var query4List = query4.ToList().OrderBy(a => a.YGBH);

            query3List.ForEach(x => dansiDailySalaries.Add(x));

         //   query4List.ForEach(x => dansiDailySalaries.Add(x));

            datagridDaily.ItemsSource = dansiDailySalaries;





        }

        private void btnGet2_Click(object sender, RoutedEventArgs e)
        {
            DateTime certainDate = Convert.ToDateTime(sfDatePicker2.Value?.ToString("yyyy-MM-dd"));

            DateTime certainDateWhiteStart = certainDate.AddHours(7);
            DateTime certainDateWhiteEnd = certainDateWhiteStart.AddHours(12);

            DateTime certainDateNightStart = certainDate.AddHours(19);
            DateTime certainDateNightEnd = certainDateNightStart.AddHours(12);


            DateTime certainDateNext = certainDate.AddDays(1);

            exportedDateTime = certainDate;


       



            zhiXianDailyOutputRepo.Clear();

            exportedDateTime = certainDate;

            //zCL = 0;
            //zGZ = 0;

            ////查询满足当前日期条件的总产量和总成本

            //var certainDayData4 = (from data in SCDBDataContent.DSZX_CPCRKB
            //                       where data.CJH == "制线" && data.RKSJ >= certainDate && data.RKSJ < certainDateNext
            //                       select data).ToList();
            //if (certainDayData4 != null && certainDayData4.Count > 0)
            //{
            //    for (int i = 0; i < certainDayData4.Count; i++)
            //    {
            //        zCL = (float)certainDayData4[i].CPZL + zCL;
            //        zGZ = (float)certainDayData4[i].HSGZ + zGZ;
            //    }
            //}

            //zhiXianDailyOutputRepo.Add(new ZhiXianDailyOutputRepo() { Runs = "白班",  SCCL = zCL/2, TotalGZ = zGZ/2, });
            //zhiXianDailyOutputRepo.Add(new ZhiXianDailyOutputRepo() { Runs = "晚班", SCCL = zCL / 2, TotalGZ = zGZ / 2, });

            //datagrid.ItemsSource = zhiXianDailyOutputRepo;


            zhiXianDailyOutputRepo.Clear();


            var certainDayWhiteData = (from data in SCDBDataContent.DSZX_CPCRKB
                                       where data.CJH == "单丝" && data.RKSJ >= certainDateWhiteStart && data.RKSJ < certainDateWhiteEnd
                                       select data).ToList();


            var queryDay = from el in certainDayWhiteData.GroupBy(x => x.CPGG)
                         select new ZhiXianDailyOutputRepo
                         {
                             Runs="白班",
                             CPGG = el.Key,
                           //  YGBH = (el.Where(a => a.YGXM == el.Key).First()).YGBH.ToString(),
                             SCCL =Math.Round( (double)(el.Sum(a => a.CPZL)),3),
                             TotalGZ =Math.Round( (double)el.Sum(x => x.HSGZ),3),
                         };
            var query3List = queryDay.ToList().OrderBy(a => a.CPGG);



            var certainDayNightData = (from data in SCDBDataContent.DSZX_CPCRKB
                                       where data.CJH == "单丝" && data.RKSJ >= certainDateNightStart && data.RKSJ < certainDateNightEnd
                                       select data).ToList();


            var queryNight = from el in certainDayNightData.GroupBy(x => x.CPGG)
                           select new ZhiXianDailyOutputRepo
                           {
                               Runs = "夜班",
                               CPGG = el.Key,
                               //  YGBH = (el.Where(a => a.YGXM == el.Key).First()).YGBH.ToString(),
                               SCCL =Math.Round( (double)(el.Sum(a => a.CPZL)),3),
                               TotalGZ =Math.Round( (double)el.Sum(x => x.HSGZ),3),
                           };
            var query4List = queryNight.ToList().OrderBy(a => a.CPGG);



            query3List.ForEach(x => zhiXianDailyOutputRepo.Add(x));

            query4List.ForEach(x => zhiXianDailyOutputRepo.Add(x));

            datagrid.ItemsSource = zhiXianDailyOutputRepo;


        }

        private void btnGet3_Click(object sender, RoutedEventArgs e)
        {
            DateTime certainDate = Convert.ToDateTime(sfDatePicker3.Value?.ToString("yyyy-MM-dd"));

            DateTime certainDateWhiteStart = certainDate.AddHours(7);
            DateTime certainDateWhiteEnd = certainDateWhiteStart.AddHours(12);

            DateTime certainDateNightStart = certainDate.AddHours(19);

            DateTime certainDateNightEnd = certainDateNightStart.AddHours(12);


            //  DateTime certainDateNext = certainDate.AddDays(1);

            DateTime certainDateNext = certainDateWhiteStart.AddDays(1);

            //最后一天的开始结束日时间段

            DateTime EndcertainDate = Convert.ToDateTime(sfDatePicker4.Value?.ToString("yyyy-MM-dd"));

            DateTime EndcertainDateWhiteStart = certainDate.AddHours(7);

            DateTime EndcertainDateNext = certainDateWhiteStart.AddDays(1);


            exportedDateTime = certainDate;


            zhiXianMultiOutputRepo.Clear();

            if (EndcertainDate < certainDate)
            {
                MessageBox.Show("结束日期不满足条件");
                return;
            }
            else
            {
                int daysCount = (EndcertainDate - certainDate).Days + 1;

                for (int i = 0; i < daysCount; i++)
                {
                  var  certainDateWhiteStart9 = certainDateWhiteStart.AddDays(i);
                   var certainDateNext9 = certainDateWhiteStart9.AddDays(1);


                    var certainDayData = (from data in SCDBDataContent.DSZX_CPCRKB
                                          where data.CJH == "单丝" && data.RKSJ >= certainDateWhiteStart9 && data.RKSJ < certainDateNext9
                                          select data).ToList();


                    var queryDay = from el in certainDayData.GroupBy(x => x.CPGG)
                                   select new ZhiXianDailyOutputRepo
                                   {
                                       DateString = certainDateWhiteStart9.ToString("yyyy-MM-dd"),
                                       CPGG = el.Key,
                                       //  YGBH = (el.Where(a => a.YGXM == el.Key).First()).YGBH.ToString(),
                                       SCCL = Math.Round((double)(el.Sum(a => a.CPZL)),3),
                                       TotalGZ = Math.Round((double)el.Sum(x => x.HSGZ),3),
                                   };
                    var query3List = queryDay.ToList().OrderBy(a => a.CPGG);
                    query3List.ForEach(x => zhiXianMultiOutputRepo.Add(x));
                }
            }



          

            exportedDateTime = certainDate;

          

          


            //var certainDayData = (from data in SCDBDataContent.DSZX_CPCRKB
            //                           where data.CJH == "制线" && data.RKSJ >= certainDateWhiteStart && data.RKSJ < certainDateNext
            //                           select data).ToList();


            //var queryDay = from el in certainDayData.GroupBy(x => x.CPGG)
            //               select new ZhiXianDailyOutputRepo
            //               {
            //                   DateString = certainDateWhiteStart.ToString("yyyy-MM-dd"),
            //                   CPGG = el.Key,
            //                   //  YGBH = (el.Where(a => a.YGXM == el.Key).First()).YGBH.ToString(),
            //                   SCCL = (double)(el.Sum(a => a.CPZL)),
            //                   TotalGZ = (double)el.Sum(x => x.HSGZ),
            //               };
            //var query3List = queryDay.ToList().OrderBy(a => a.CPGG);
            //query3List.ForEach(x => zhiXianMultiOutputRepo.Add(x));





            datagridMulti.ItemsSource = zhiXianMultiOutputRepo;
        }

        private void btnGet4_Click(object sender, RoutedEventArgs e)
        {
            DateTime certainDate = Convert.ToDateTime(sfDatePicker3.Value?.ToString("yyyy-MM-dd"));

            DateTime certainDateWhiteStart = certainDate.AddHours(7);
            DateTime certainDateWhiteEnd = certainDateWhiteStart.AddHours(12);

            DateTime certainDateNightStart = certainDate.AddHours(19);

            DateTime certainDateNightEnd = certainDateNightStart.AddHours(12);
          

            DateTime certainDateNext = certainDateWhiteStart.AddDays(1);

            //最后一天的开始结束日时间段

            DateTime EndcertainDate = Convert.ToDateTime(sfDatePicker4.Value?.ToString("yyyy-MM-dd"));

            DateTime EndcertainDateWhiteStart = EndcertainDate.AddHours(7);

            DateTime EndcertainDateNext = EndcertainDateWhiteStart.AddDays(1);



            var filePath = @"d:\产量\";
            var fileName = $"计件工资表{certainDate.ToString("yyyyMMddHHmmss")}.xlsx";

            zhiXianPeriodOutputSalaryRepo.Clear();

            var certainDayData = (from data in SCDBDataContent.DSZX_CPCRKB
                                  where data.CJH == "单丝" && data.RKSJ >= certainDateWhiteStart && data.RKSJ < EndcertainDateNext
                                  select data).ToList();



            List<string> groupNames  = certainDayData.GroupBy(p => p.CPGG).Select(g => g.Key).ToList();            



            var queryDay34 = certainDayData.
                     GroupBy(x => x.CPGG)
                     .Select(group1 => new {
                         CPGG = group1.Key,
                         CPGGGroup= group1.ToList(),
                         NameGroup = group1.GroupBy(s => s.CZR)
                                         .Select(group2 => new 
                                         {
                                             CZR = group2.Key,
                                             LISTCZR=group2.ToList(),
                                         })

                     });

            foreach (var firstGroupItem in queryDay34)
            {
                //对于 firstGroupItem   
                zhiXianPeriodOutputSalaryRepo.Add(new ZhiXianPeriodOutputSalaryRepo()
                {
                    RowLabel = firstGroupItem.CPGG,
                    SCCL = (double)(firstGroupItem.CPGGGroup.Sum(a => a.CPZL)),
                    TotalGZ = (double)firstGroupItem.CPGGGroup.Sum(x => x.HSGZ),
                });

                foreach (var secondGroupItem in firstGroupItem.NameGroup)
                {
                    zhiXianPeriodOutputSalaryRepo.Add(new ZhiXianPeriodOutputSalaryRepo()
                    {
                        RowLabel = secondGroupItem.CZR,
                        SCCL = (double)(secondGroupItem.LISTCZR.Sum(a => a.CPZL)),
                        TotalGZ = (double)secondGroupItem.LISTCZR.Sum(x => x.HSGZ),
                    });
                }
            }

            zhiXianPeriodOutputSalaryRepo.Add(new ZhiXianPeriodOutputSalaryRepo()
            {
                RowLabel = "总计",
                SCCL = (double)(certainDayData.Sum(a => a.CPZL)),
                TotalGZ = (double)certainDayData.Sum(x => x.HSGZ),
            });

        

            //   var dataTable = ConvertToDataTable(zhiXianPeriodOutputSalaryRepo);


            //  var query3List = queryDay.ToList().OrderBy(a => a.RowLabel);
            //  query3List.ForEach(x => zhiXianPeriodOutputSalaryRepo.Add(x));


            var dataTable = new DataTable();
            dataTable.Columns.Add("行标签");
            dataTable.Columns.Add("求和项：产量");
            dataTable.Columns.Add("求和项：产量工资");


            for (int i = 0; i < zhiXianPeriodOutputSalaryRepo.Count; i++)
            {
                DataRow dataRow = dataTable.NewRow();
                dataRow[0] = zhiXianPeriodOutputSalaryRepo[i].RowLabel;
                dataRow[1] = zhiXianPeriodOutputSalaryRepo[i].SCCL;
                dataRow[2] = zhiXianPeriodOutputSalaryRepo[i].TotalGZ;
                dataTable.Rows.Add(dataRow);
            }



           
            //DataRow dataRow1 = dataTable.NewRow();
            //dataRow1[0] = "张123456789";
            //dataRow1[1] = "11111111111111111111111111111111111";
            //dataRow1[2] = "222222222222222222222222222";
            //dataTable.Rows.Add(dataRow1);



            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
            // 创建一个Excel文件
            using (ExcelPackage excelPackage = new ExcelPackage())
            {
                // 添加一个工作表
                ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("MySheet");

                // 添加标题
                worksheet.Cells["A1"].Value = "计件工资表";
                worksheet.Cells["A1"].Style.Font.Size = 20;
                worksheet.Cells["A1"].Style.Font.Bold = true;


                // var filePath = @"d:\产量\";
                //  var fileName = $"计件工资表{certainDate.ToString("yyyyMMddHHmmss")}.xlsx";
                string dateRangeStr = $"从 {certainDate.ToString("yyyy-MM-dd")} 到 {EndcertainDate.ToString("yyyy-MM-dd")}";
                // 添加时间
                //  worksheet.Cells["C1"].Value = "Date: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                worksheet.Cells["C1"].Value = dateRangeStr;

                // 合并单元格以显示标题
                worksheet.Cells["A1:B1"].Merge = true;
                // 设置合并单元格文本水平和垂直对齐方式为居中
                worksheet.Cells["A1"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                worksheet.Cells["A1"].Style.VerticalAlignment = ExcelVerticalAlignment.Center;

                // 将DataTable数据写入工作表
                worksheet.Cells["A2"].LoadFromDataTable(dataTable, true);
                // 自适应单元格宽度
                worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();

                // 设置标题行样式：红色加粗边框
                using (ExcelRange titleRange = worksheet.Cells[2, 1, 2, dataTable.Columns.Count])
                {
                    titleRange.Style.Font.Bold = true;
                    //titleRange.Style.Font.Color.SetColor(System.Drawing.Color.Red);

                    // 设置上边框
                    titleRange.Style.Border.Top.Style = ExcelBorderStyle.Thick;
                    titleRange.Style.Border.Top.Color.SetColor(System.Drawing.Color.Red);

                    // 设置下边框
                    titleRange.Style.Border.Bottom.Style = ExcelBorderStyle.Thick;
                    titleRange.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Red);

                    // 设置第一个单元格的左边框
                    titleRange[2, 1].Style.Border.Left.Style = ExcelBorderStyle.Thick;
                    titleRange[2, 1].Style.Border.Left.Color.SetColor(System.Drawing.Color.Red);

                    // 设置最后一个单元格的右边框
                    titleRange[2, dataTable.Columns.Count].Style.Border.Right.Style = ExcelBorderStyle.Thick;
                    titleRange[2, dataTable.Columns.Count].Style.Border.Right.Color.SetColor(System.Drawing.Color.Red);
                }

                int totalRowIndex = dataTable.Rows.Count + 2;
                // 设置尾行样式：红色加粗边框
                using (ExcelRange titleRange = worksheet.Cells[totalRowIndex, 1, totalRowIndex, dataTable.Columns.Count])
                {
                    titleRange.Style.Font.Bold = true;
                    //titleRange.Style.Font.Color.SetColor(System.Drawing.Color.Red);

                    // 设置上边框
                    titleRange.Style.Border.Top.Style = ExcelBorderStyle.Thick;
                    titleRange.Style.Border.Top.Color.SetColor(System.Drawing.Color.Red);

                    // 设置下边框
                    titleRange.Style.Border.Bottom.Style = ExcelBorderStyle.Thick;
                    titleRange.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Red);

                    // 设置第一个单元格的左边框
                    titleRange[totalRowIndex, 1].Style.Border.Left.Style = ExcelBorderStyle.Thick;
                    titleRange[totalRowIndex, 1].Style.Border.Left.Color.SetColor(System.Drawing.Color.Red);

                    // 设置最后一个单元格的右边框
                    titleRange[totalRowIndex, dataTable.Columns.Count].Style.Border.Right.Style = ExcelBorderStyle.Thick;
                    titleRange[totalRowIndex, dataTable.Columns.Count].Style.Border.Right.Color.SetColor(System.Drawing.Color.Red);
                }

                // 设置偶数行样式：红色背景底色
                //for (int i = 2; i < dataTable.Rows.Count + 1; i++)
                //{
                //    if (i % 2 != 0)
                //    {
                //        using (ExcelRange totalRange = worksheet.Cells[i, 1, i, dataTable.Columns.Count])
                //        {
                //            totalRange.Style.Fill.PatternType = ExcelFillStyle.Solid;
                //            totalRange.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightPink);
                //        }
                //    }
                //}
                // 保存Excel文件

                //  var filePath = @"d:\产量\";
                //  var fileName = $"计件工资表{certainDate.ToString("yyyyMMddHHmmss")}.xlsx";

                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                string  excelPath = $"{filePath}{fileName}";
                // excelPackage.SaveAs(new FileInfo("output.xlsx"));
                excelPackage.SaveAs(new FileInfo(excelPath));
            }

            MessageBox.Show(@"已成功导出到D:\产量\！");


        }

        private static DataTable ConvertToDataTable<T>(ObservableCollection<T> collection) where T : class
        {
            var table = new DataTable();

            if (collection == null || collection.Count <= 0) return table;

            // 根据第一个元素的属性动态地创建表头
            var firstElementProperties = typeof(T).GetProperties();
            foreach (var propertyInfo in firstElementProperties)
            {
                table.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType);
            }

            // 将集合中的每个元素添加到表中
            foreach (var item in collection)
            {
                var row = table.NewRow();

                for (int i = 0; i < firstElementProperties.Length; i++)
                {
                    var value = firstElementProperties[i].GetValue(item);

                    if (!Convert.IsDBNull(value))
                    {
                        row[firstElementProperties[i].Name] = value;
                    }
                }

                table.Rows.Add(row);
            }

            return table;
        }
    }
}
